import { useRef, useMemo } from "react";
import { extend, useFrame, useLoader, useThree } from "@react-three/fiber";
import { Water } from "three-stdlib";
import * as THREE from "three";

// 海洋平面
extend({ Water });
export default function Ocean(): any {
  const ref: any = useRef();
  const gl: any = useThree((state) => state.gl);

  const waterNormals = useLoader(THREE.TextureLoader, "./waters.jpeg");
  waterNormals.wrapS = waterNormals.wrapT = THREE.RepeatWrapping;
  const geom = useMemo(() => new THREE.PlaneGeometry(1000, 1000), []);
  const config = useMemo(
    () => ({
      textureWidth: 512,
      textureHeight: 512,
      waterNormals,
      sunDirection: new THREE.Vector3(),
      sunColor: 0xffffff, // 太阳的颜色
      // waterColor: 0x001e0f, // 水的颜色
      waterColor: "skyblue", // 水的颜色
      distortionScale: 3.7,
      fog: false,
      format: gl.encoding,
    }),
    [waterNormals]
  );

  useFrame((state, delta) => {
    if (!state) return;
    ref.current.material.uniforms.time.value += delta;
  });

  return (
    <water
      ref={ref}
      args={[geom, config]}
      rotation-x={-Math.PI / 2}
      position={[20, -5.5, -100]}
    />
  );
}
declare global {
  namespace JSX {
    interface IntrinsicElements {
      water: any;
    }
  }
}
